/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package wechat

import (
	"bytes"
	"encoding/json"
	"net/http"
	"io"
	"encoding/xml"
)

func GetJson(Url string, response interface{}) (err error) {
	resp, err := http.Get(Url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	buf := bytes.NewBuffer(nil)
	_, err = io.Copy(buf, resp.Body)
	if err != nil {
		return err
	}
	var werr Error
	data := buf.Bytes()
	json.Unmarshal(data, &werr)
	if werr.ErrCode != 0 {
		return werr
	}
	if response != nil {
		return json.Unmarshal(data, response)
	} else {
		return nil
	}
}

func PostJson(Url string, parameter, response interface{}) (err error) {
	var buf *bytes.Buffer
	if parameter != nil {
		buf = bytes.NewBuffer(nil)
		encoder := json.NewEncoder(buf)
		encoder.SetEscapeHTML(false)
		err = encoder.Encode(parameter)
		if err != nil {
			return err
		}
	}
	resp, err := http.Post(Url, "application/json;charset=utf-8", buf)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	buf = bytes.NewBuffer(nil)
	_, err = io.Copy(buf, resp.Body)
	if err != nil {
		return err
	}
	var werr Error
	data := buf.Bytes()
	json.Unmarshal(data, &werr)
	if werr.ErrCode != 0 {
		return werr
	}
	if response != nil {
		return json.Unmarshal(data, response)
	} else {
		return nil
	}
}

func PostXml(url string, parameter, response interface{}) error {
	buf := bytes.NewBuffer(nil)
	encoder := xml.NewEncoder(buf)
	err := encoder.Encode(parameter)
	if err != nil {
		return err
	}
	resp, err := http.Post(url, "application/xml;charset=utf-8", buf)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	buf = bytes.NewBuffer(nil)
	_, err = io.Copy(buf, resp.Body)
	if err != nil {
		return err
	}
	var werr Error
	data := buf.Bytes()
	xml.Unmarshal(data, &werr)
	if werr.ErrCode != 0 {
		return werr
	}
	if response != nil {
		return xml.Unmarshal(data, response)
	} else {
		return nil
	}
}
